#!/bin/sh

send_message(){
        rupor_id=$1
        content=$2
        curl -k -s -X POST -H "Charset: UTF-8" $api/sendMessage -d chat_id=$rupor_id -d "text=$content" >> /dev/null
}

reply_message(){
        rupor_id=$1
        content=$2
        message_id=$3
        curl -k -s -X POST -H "Charset: UTF-8" $api/sendMessage -d chat_id=$rupor_id -d text=$content -d reply_to_message_id=$message_id >> /dev/null
}

token=$(uci get telegram-wol.auth.token)
rupors=$(uci get telegram-wol.auth.rupors)
api=https://api.telegram.org/bot$token
update_rate=$(uci get telegram-wol.config.update_rate)
offset_file=/tmp/tgoffset

offset=0
if [ -f "$offset_file" ]; then
        offset=$( cat $offset_file )
else
        echo $offset > $offset_file
fi



while [ true ]
do
        updates=$(curl -s -k -X GET ${api}/getUpdates -d offset=$offset)
        status=$(jsonfilter -s "$updates" -e $.ok)

        if [ $status != 'true' ]; then
                sleep 10
                continue;
        fi

        for update_id in $(jsonfilter -s "$updates" -e $.result[*].update_id)
        do
                offset=$((update_id+1))
                echo $offset > $offset_file

                sender=$(jsonfilter -s "$updates"  -e "$.result[@.update_id=$update_id].message.chat.id")
                if ! echo $rupors | grep -w $sender >> /dev/null; then
                        logger -t telegram-wol "$(jsonfilter -s "$updates"  -e "$.result[@.update_id=$update_id].message.from.username") ($sender) tried to access bot"
                        send_message $sender "Who are you?"
                        sleep $update_rate
                        continue;
                fi

                type=$(jsonfilter -s "$updates" -e "$.result[@.update_id=$update_id].message.entities[*].type")
                if [ "$type" != "bot_command" ]; then
                        logger -t telegram-wol "$sender input a wrong command"
                        send_message $sender "This is not a command"
                        sleep $update_rate
                        continue;
                fi

                command=$(jsonfilter -s "$updates" -e "$.result[@.update_id=$update_id].message.text")
                case $command in
                        ("/start")
                                etherwake -i $(uci get telegram-wol.config.interface) $(uci get telegram-wol.config.mac_address)
                                logger -t telegram-wol "$sender activated $command"
                                send_message $sender "Turning on, your ip: $(curl ifconfig.me)"
                                ;;
                        (*)
                                send_message $sender "$command not found"
                                logger -t telegram-wl "$sender input an invalid command ($command)"
                                ;;
                esac
        done
        sleep $update_rate
done &
